package cn.org.intelli.zffserver.controller;

import cn.org.intelli.zffserver.aop.AuthenticationTicket;
import cn.org.intelli.zffserver.domain.BackBean;
import cn.org.intelli.zffserver.entity.JobEntity;
import cn.org.intelli.zffserver.entity.ModelEntity;
import cn.org.intelli.zffserver.repository.JobRepository;
import cn.org.intelli.zffserver.repository.ModelRepository;
import cn.org.intelli.zffserver.service.DeleteJobService;
import cn.org.intelli.zffserver.service.JobService;
import cn.org.intelli.zffserver.util.Uid;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import dm.jdbc.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.util.*;

@RestController
@RequestMapping({"/job"})
@Slf4j
public class JobController {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private JobService jobServce;

    @Autowired
    private ModelRepository modelRepository;

    @Autowired
    private GroupTemplate groupTemplate;

    @Autowired
    private DeleteJobService deleteJobService;

//
//    @PostMapping({"/deleteJob/{jobId}"})
//    public BackBean<String> deleteJob(@PathVariable("jobId") String jobId) {
//        try {
//            /*  62 */
//            this.jobServce.deleteJob(jobId);
//            /*  63 */
//            return BackBean.builder().status(true).data("success").build();
//            /*  64 */
//        } catch (Exception e) {
//            /*  65 */
//            e.printStackTrace();
//            /*  66 */
//            log.error("@DeleteJob: error is {}", e.getMessage());
//            /*  67 */
//            return BackBean.builder().status(false).message(e.getMessage()).build();
//        }
//    }
//
//
//    @GetMapping({"/getJobDetail"})
//    public BackBean<JSONObject> getJobDetail(@RequestParam("jobId") String jobId) {
//        try {
//            /*  79 */
//            JobEntity jobEntity = this.jobRepository.findById(jobId).get();
//            /*  80 */
//            ModelEntity model = this.modelRepository.findById(jobEntity.getModelId()).get();
//            /*  81 */
//            JSONArray resultMeta = JSONArray.parseArray(model.getResultMeta());
//            /*  82 */
//            JSONObject result = JSON.parseObject(JSON.toJSONString(jobEntity));
//            /*  83 */
//            result.put("resultMeta", resultMeta);
//            /*  84 */
//            result.put("param", JSON.parseObject(jobEntity.getParam()));
//            /*  85 */
//            result.put("resultType", model.getModelType());
//            /*  86 */
//            return BackBean.builder().status(true).data(result).build();
//            /*  87 */
//        } catch (Exception e) {
//            /*  88 */
//            e.printStackTrace();
//            /*  89 */
//            log.error("@GetJobDetail: error is {}", e.getMessage());
//            /*  90 */
//            return BackBean.builder().status(false).message(e.getMessage()).build();
//        }
//    }


    @GetMapping({"/getJobList"})
    public BackBean<JSONArray> getJobList(@RequestParam(name = "page", defaultValue = "1") Integer page, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, @Param("modelId") String modelId) {
        try {
            /* 106 */
            String userPin = AuthenticationTicket.getTicket().getPin();
            /* 107 */
            Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC, "createTime"));
            /* 108 */
            PageRequest pageRequest = PageRequest.of(page.intValue() - 1, pageSize.intValue(), sort);
            /* 109 */
//            Page<JobEntity> jobPage = this.jobRepository.findAll((Specification) new Object(this,  userPin, modelId), (Pageable) pageRequest);
            Specification<JobEntity> specification = (root, query, criteriaBuilder) -> {
                List<Predicate> predicates = new ArrayList<>();

                // 添加用户权限条件
                if (StringUtils.isNotBlank(userPin)) {
                    predicates.add(criteriaBuilder.equal(root.get("userPin"), userPin));
                }

                // 添加模型ID条件
                if (StringUtils.isNotBlank(modelId)) {
                    predicates.add(criteriaBuilder.equal(root.get("modelId"), modelId));
                }

                return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
            };

            Page<JobEntity> jobPage = this.jobRepository.findAll(specification, pageRequest);

            Map<String, JSONArray> modelResultMetaCache = new HashMap<>();
            /* 126 */
            Map<String, String> modelTypeCache = new HashMap<>();
            /* 127 */
            Map<String, String> modelNameCache = new HashMap<>();
            /* 128 */
            JSONArray result = new JSONArray();
            /* 129 */
            Set<String> modelIds = new HashSet<>();
            /* 130 */
            jobPage.getContent().forEach(job -> modelIds.add(job.getModelId()));


            /* 133 */
            List<String> modelIdsTmp = new ArrayList<>(modelIds);
            /* 134 */
            this.modelRepository.findAllByIdIn(modelIdsTmp).forEach(model -> {
                modelResultMetaCache.put(model.getId(), JSONArray.parseArray(model.getResultMeta()));

                modelTypeCache.put(model.getId(), model.getModelType());
                modelNameCache.put(model.getId(), model.getModelName());
            });
            /* 140 */
            jobPage.getContent().forEach(job -> {
                JSONObject atom = JSON.parseObject(JSON.toJSONString(job));

                atom.put("resultMeta", modelResultMetaCache.get(job.getModelId()));
                atom.put("param", JSON.parseObject(job.getParam()));
                atom.put("resultType", modelTypeCache.get(job.getModelId()));
                atom.put("modelName", modelNameCache.get(job.getModelId()));
                result.add(atom);
            });
            /* 149 */
            return BackBean.<JSONArray>builder()
/* 150 */.status(true)
/* 151 */.totalNum(Long.valueOf(jobPage.getTotalElements()))
/* 152 */.data(result).build();
            /* 153 */
        } catch (Exception e) {
            /* 154 */
            e.printStackTrace();
            /* 155 */
            log.error("@GetJobList: error is {}", e.getMessage());
            /* 156 */
            return BackBean.<JSONArray>builder().status(false).message(e.getMessage()).build();
        }
    }


    @PostMapping({"/createJobAndExecute"})
    public BackBean<String> createJobAndExecute(@RequestBody JSONObject jobJson) {
        try {
            JobEntity jobEntity = JSON.toJavaObject(jobJson, JobEntity.class);

            /* 169 */
            if (StringUtil.isEmpty(jobEntity.getModelId())) {
                /* 170 */
                throw new Exception("案件标识或模型标识为空");
            }
            /* 172 */
            ModelEntity model = this.modelRepository.findById(jobEntity.getModelId()).get();
            /* 173 */
            JSONArray paramMeta = new JSONArray();
            /* 174 */
            if (StringUtil.isNotEmpty(model.getParamMeta())) {
                /* 175 */
                paramMeta.addAll(JSON.parseArray(model.getParamMeta()));
            }
            /* 177 */
            JSONObject defalutParam = new JSONObject();
            /* 178 */
            if (StringUtil.isNotEmpty(model.getDefaultParam())) {
                /* 179 */
                defalutParam.putAll(JSON.parseObject(model.getDefaultParam()));
            }
            /* 181 */
            String sqlTemplate = model.getSql();

            /* 183 */
            String id = Uid.generateShortUuid();
            /* 184 */
            log.info("@CreateJobAndExecute: 创建新任务， id为{}", id);
            /* 185 */
            jobEntity.setCreateTime(new Date());
            /* 186 */
            jobEntity.setUserPin(AuthenticationTicket.getTicket().getPin());
            /* 187 */
            jobEntity.setStatus("CREATED");
            /* 188 */
            jobEntity.setId(id);
            /* 189 */
            jobEntity.setSourceDbId(model.getSourceDbId());
            /* 190 */
            jobEntity.setDestinationDbId(model.getDestinationDbId());
            /* 191 */
            jobEntity.setJobExecuter(model.getModelExecuter());


            /* 194 */
            JSONObject jobParam = new JSONObject();
            /* 195 */
            if (StringUtil.isNotEmpty(jobEntity.getParam())) {
                /* 196 */
                jobParam.putAll(JSON.parseObject(jobEntity.getParam()));
            }
            /* 198 */
            List<String> unCacheParamName = new ArrayList<>();
            /* 199 */
            for (int i = 0; i < paramMeta.size(); i++) {
                /* 200 */
                JSONObject atom = paramMeta.getJSONObject(i);
                /* 201 */
                Boolean needed = atom.getBoolean("needed");
                /* 202 */
                if (needed != null && needed.booleanValue()) {


                    /* 205 */
                    String paramName = atom.getString("name");
                    /* 206 */
                    if (!jobParam.containsKey(paramName)) {

                        /* 209 */
                        if (defalutParam.containsKey(paramName)) {
                            /* 210 */
                            jobParam.put(paramName, defalutParam.get(paramName));
                        } else {
                            /* 212 */
                            unCacheParamName.add(paramName);
                        }
                    }
                }
            }
            /* 216 */
            if (unCacheParamName.size() > 0) {

                /* 218 */
                jobEntity.setStatus("CREATE_FAILED");
                /* 219 */
                String message = String.join(",", unCacheParamName) + "参数未传递";
                /* 220 */
                jobEntity.setMessage(message);
                /* 221 */
                this.jobRepository.save(jobEntity);
                /* 222 */
                throw new Exception(message);
            }
            /* 224 */
            jobEntity.setParam(jobParam.toJSONString());


            /* 227 */
            Template t = this.groupTemplate.getTemplate(sqlTemplate);
            /* 228 */
            t.binding(jobParam);
            /* 229 */
            log.info(jobParam.toJSONString());
            /* 230 */
            String jobSql = t.render();
            /* 231 */
            jobEntity.setSql(jobSql);

            /* 233 */
            this.jobRepository.save(jobEntity);

            /* 235 */
            log.info("CreateJobAndExecute: 开始执行任务， id为{}", id);

            /* 237 */
            this.jobServce.jobExecute(jobEntity);
            /* 238 */
            return BackBean.<String>builder().status(true).data("success").build();
            /* 239 */
        } catch (Exception e) {
            /* 240 */
            e.printStackTrace();
            /* 241 */
            log.error("@CreateJob: error is {}", e.getMessage());
            /* 242 */
            return BackBean.<String>builder().status(false).message(e.getMessage()).build();
        }
    }


//    @PostMapping({"/jobCallback"})
//    public BackBean<String> jobCallback(@RequestBody JSONObject jobStatus) {
//        try {
//            /* 254 */
//            String jobId = jobStatus.getString("jobId");
//            /* 255 */
//            String status = jobStatus.getString("status");
//            /* 256 */
//            String message = jobStatus.getString("message");
//            /* 257 */
//            log.info("@JobCallback: Job {} 计算完成，计算状态为{}", jobId, status);
//
//            /* 259 */
//            JobEntity job = this.jobRepository.findById(jobId).get();
//            /* 260 */
//            job.setStatus(status);
//            /* 261 */
//            if (StringUtil.isNotEmpty(message)) {
//                /* 262 */
//                job.setMessage(message);
//            }
//            /* 264 */
//            this.jobRepository.save(job);
//            /* 265 */
//            return BackBean.builder().status(true).data("success").build();
//            /* 266 */
//        } catch (Exception e) {
//            /* 267 */
//            e.printStackTrace();
//            /* 268 */
//            log.error("@JobCallBack: error is {}", e.getMessage());
//            /* 269 */
//            return BackBean.builder().status(false).message(e.getMessage()).build();
//        }
//    }
//
//    @GetMapping({"/getJobQueue"})
//    public BackBean<String> getJobQueue() {
//        /* 275 */
//        return BackBean.builder().status(true).data(JobQueue.getJobQueueSize().toString()).build();
//    }
//
//    @GetMapping({"/clearDeletedJobResult"})
//    public BackBean<String> clearDeletedJobResult() {
//        try {
//            /* 281 */
//            this.deleteJobService.clearJobResult();
//            /* 282 */
//            return BackBean.builder().status(true).data("success").build();
//            /* 283 */
//        } catch (Exception e) {
//            /* 284 */
//            e.printStackTrace();
//            /* 285 */
//            log.error("@ClearDeletedJobResult: error is {}", e.getMessage());
//            /* 286 */
//            return BackBean.builder().status(false).message(e.getMessage()).build();
//        }
//    }
}


/* Location:              C:\Users\admin\Desktop\xxm\zjg11\ZjgCaculate-v1.0.jar!\BOOT-INF\classes\cn\org\intelli\zffserver\controller\JobController.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */